package com.infovane.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.infovane.base.BaseAction;
import com.infovane.model.PageModel;
import com.infovane.model.TArticle;
import com.infovane.model.TArticleComment;
import com.infovane.model.TUser;
import com.infovane.model.TUserAttention;
import com.infovane.service.ArticleCommentService;
import com.infovane.service.ArticleService;
import com.infovane.service.UserAttentionService;
import com.infovane.service.UserService;
import com.infovane.utils.PagingModule;
import com.infovane.utils.SystemConstant;

public class UserAction extends BaseAction{
	
	private ArticleCommentService articleCommentService;
	
	
	
	public ArticleCommentService getArticleCommentService() {
		return articleCommentService;
	}



	public void setArticleCommentService(ArticleCommentService articleCommentService) {
		this.articleCommentService = articleCommentService;
	}
	
	private ArticleService articleService;
	
	



	public ArticleService getArticleService() {
		return articleService;
	}



	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}
	private UserService userService;
	
	



	public UserService getUserService() {
		return userService;
	}



	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private UserAttentionService userAttentionService;
	
	
	

	public UserAttentionService getUserAttentionService() {
		return userAttentionService;
	}



	public void setUserAttentionService(UserAttentionService userAttentionService) {
		this.userAttentionService = userAttentionService;
	}



	/**
	 * 用户发表文章评论
	 * */
	public String issueComment(){
		
		Long articleid=0L;
		try{
			articleid=Long.parseLong(httpServletRequest.getParameter("articleId"));
		}catch(NullPointerException e){
			String warn="发表评论出错!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}catch(Exception e){
			String warn="发表评论出错!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}
		String articletitle=(String)httpServletRequest.getParameter("articleTitle");
		String content=(String)httpServletRequest.getParameter("content");
		if(articletitle==null||articletitle.equals("")){
			String warn="评论标题不能为空";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else if(content==null||content.equals("")){
			String warn="评论内容不能为空";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else{
			TArticle article=new TArticle();
			article=(TArticle) this.articleService.get(TArticle.class,articleid);
			try{
				article.setArticleSumComment(article.getArticleSumComment()+1);
			}catch(NullPointerException e){
				article.setArticleSumComment(1);
			}
			this.articleService.update(article);
			String username=(String)httpServletRequest.getSession().getAttribute("USERNAME");
			TArticleComment comment=new TArticleComment();
			if(username==null||username.equals("")){
				comment.setCommentIfHide(1);
				comment.setUserName("匿名用户");
			}else{
				comment.setCommentIfHide(0);
				comment.setUserName(username);
			}
			comment.setArticleCommentContent(content);
			comment.setArticleCommentTitle(articletitle);
			comment.setArticleId(articleid);
			comment.setCommentCreateTime(new Date());
			comment.setCommentIsLeaf(0);
			comment.setCommentPId(0L);
			comment.setCommentRootId(0L);
			boolean sign=this.articleCommentService.add(comment);
			if(sign){
				String warn="感谢您对本文的评论!";
				httpServletRequest.setAttribute("WARN", warn);
				return SUCCESS;
			}
			return ERROR;
		}
		
	}	
	/**
	 * 用户注册检测
	 * @throws IOException 
	 * */
	public String checkUsername() throws IOException{
		String responseText="";
		String username=(String)httpServletRequest.getParameter("username");
		httpServletResponse.setContentType("text/plain");
		httpServletResponse.setCharacterEncoding("UTF-8");
		TUser user=new TUser();
		user=this.userService.getUser(username);
		//httpServletResponse.setContentType("text/html;charset=UTF-8");
		//httpServletRequest.setCharacterEncoding("UTF-8");
	
		PrintWriter out=httpServletResponse.getWriter();
		if(user!=null){
			responseText="该用户名已经被占用!";
		}else{
			responseText="恭喜您,该用户名可用!";
		}
		out.println(responseText);
		out.flush();
		out.close();
		return null;
		//httpServletResponse.getWriter().write("22，<a href=t1.htm>ok</a>222");
	}
	
	/**
	 * 用户注册
	 * */
	public String regist(){
		String username=(String)httpServletRequest.getParameter("username");
		String password=(String)httpServletRequest.getParameter("password");
		String password2=(String)httpServletRequest.getParameter("password2");
		if(username==null||username.equals("")){
			String warn="用户名不能为空！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
			
		}else if(password==null||password.equals("")){
			String warn="密码不能为空！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else if(password2==null||password==""){
			String warn="第二个密码不能为空!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else if(!password.equals(password2)){
			String warn="两次输入的密码不一致!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
			
		}else{
			String ip = httpServletRequest.getHeader("x-forwarded-for");
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		    	ip = httpServletRequest.getHeader("Proxy-Client-IP");
		    }
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		        ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
		    }
		    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		        ip = httpServletRequest.getRemoteAddr();
		    }
			//System.out.println("ip="+ip);
			TUser user=new TUser();
			user.setUserAccountNotes("新注册用户!");
			user.setUserAccountStatus(1);//1表示用户可用
			//user.setUserAddress("not");
			user.setUserAdminLimit(0);
			//user.setUserAge(0);
			//user.setUserAuthorLevel(0);
			//user.setUserAuthorName("not");
			//user.setUserCertificate("not");
			//user.setUserCertificateNumber(0L);
			user.setUserCreateTime(new Date());
			//user.setUserEmail("not");
			//user.setUserGraduate("not");
			//user.setUserGroup("not");
			user.setUserHeadName("default");
			user.setUserHeadUrl("images/header/user.png");
			user.setUserHonorName("鸟蛋");
			user.setUserIfAdmin(0);
			//user.setUserIfAuthor(0);
			user.setUserIfLogin(0);
			//user.setUserIfVip(0);
			user.setUserIntegral(0);
			user.setUserLocationIp(ip);
			//user.setUserMood("not");
			//user.setUserMotto("not");
			user.setUserName(username);
			//user.setUserNickName("not");
			user.setUserPass(password);
			//user.setUserVipLevel(0);
			boolean sign=this.userService.add(user);
			if(sign){
				return SUCCESS;
			}
			return ERROR;
		}
		
	}
	
	/**
	 * 用户登陆
	 * */
	public String login(){
		String username=(String)httpServletRequest.getParameter("username");
		String password=(String)httpServletRequest.getParameter("password");
		if(username==null||username.equals("")){
			String warn="用户名不能为空！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
			
		}else if(password==null||password.equals("")){
			String warn="密码不能为空！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else{
			TUser user=new TUser();
			user=this.userService.getUser(username, password);
			if(user==null){
				String warn="账号或密码出错!";
				httpServletRequest.setAttribute("WARN", warn);
				return ERROR;
			}
			httpServletRequest.getSession().setAttribute("USER", user);//用户session对象
			httpServletRequest.getSession().setAttribute("USERNAME",user.getUserName());//用户名session对象
			httpServletRequest.getSession().setMaxInactiveInterval(1800);
			String result=getUserAttention(user.getUserId());// 根据用户ID获取用户资讯关注类型
			getUserAttentionArticle(result);
     		httpServletRequest.setAttribute("UATTENTION",result);
			staUserIssueArticle(username);//统计用户发表文章数
			staUserIssueComment(username);//统计用户发表评论数 
			return SUCCESS;
		}
	}
	
	/**
	 * 用户退出
	 * */
	public String logout(){
		httpServletRequest.getSession().invalidate();
		return SUCCESS;
	}
	
	/**
	 * 根据用户的资讯关注类型为用户推送文章
	 * */
	public String getUserAttentionArticle(String attentioneType){
		String strCurrentPage=httpServletRequest.getParameter("currentPage");
		int currentPage;
		if(strCurrentPage==null||strCurrentPage.equals("")){
			currentPage=1;
		}else{
			try{
				currentPage=Integer.parseInt(strCurrentPage.intern());
			}catch(NumberFormatException e){
				currentPage=1;
			}
		}
		List<TArticle> articleList=new ArrayList<TArticle>();
		int count=this.articleService.getCount(null, attentioneType);
		articleList=this.articleService.getUserArticleList(currentPage, SystemConstant.USER_ATTENTION_ARTICLE_SIZE, null, attentioneType);
		int maxPage=PagingModule.maxPageSize(count);
		PageModel<TArticle> pm=new PageModel<TArticle>(articleList,maxPage);
		httpServletRequest.setAttribute("pm", pm);
		return SUCCESS;
		
	}
	
	
	/**
	 * 统计用户发表文章数
	 * */
	public void staUserIssueArticle(String username){
		int countArticle=this.articleService.getCount(username,null);
		httpServletRequest.setAttribute("COUNTARTICLE", countArticle);
	}
	
	/**
	 * 统计用户发表评论数 
	 */
	public void staUserIssueComment(String username){
		int countComment=this.articleCommentService.getCount(username);
		httpServletRequest.setAttribute("COUNTCOMMENT", countComment);
		
	}
	/**
	 * 根据用户ID获取用户资讯关注类型
	 * */
	public String getUserAttention(Long userId){
		//该用户还没有设置资讯关注类型
		String result=null;
		TUserAttention userAttention=new TUserAttention();	
		userAttention=this.userAttentionService.getUserAttention(userId);
		if(userAttention!=null){
			return result=userAttention.getAttentionArticleType();//返回用户已经设置的资讯关注类型
		}else{
			httpServletRequest.setAttribute("UATTENTION",null);
			return result;//该用户还没有设置资讯关注类型
		}
	}
	
	/**
	 * 根据传入的参数修改用户信息
	 */
	public String userModify(){
		int condition;
		Long userId;
		try{
			condition=Integer.parseInt(httpServletRequest.getParameter("condition"));
			userId=Long.parseLong(httpServletRequest.getParameter("userId"));
		}catch(NullPointerException e){
			String warn="请勿非法操作，谢谢！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}
		if(condition==1){//condition=1,用户修改个人资料操作
			int age=Integer.parseInt(httpServletRequest.getParameter("age"));
			String nickname=(String)httpServletRequest.getParameter("nickname");
			String sex=(String)httpServletRequest.getParameter("sex");
			Long qq=Long.parseLong(httpServletRequest.getParameter("qq"));
			String email=(String)httpServletRequest.getParameter("email");
			String motto=(String)httpServletRequest.getParameter("motto");
			TUser user=new TUser();
			user=this.userService.getUser(TUser.class, userId);
			user.setUserId(userId);
			user.setUserAge(age);
			user.setUserEmail(email);
			user.setUserMotto(motto);
			user.setUserNickName(nickname);
			user.setUserSex(sex);
			user.setUserQq(qq);
			user.setUserModifyTime(new Date());
			boolean sign=this.userService.update(user);
			if(!sign){
				String warn="更新用户信息出错!";
				httpServletRequest.setAttribute("WARN", warn);
				return ERROR;
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 创建用户关注的文章类型
	 * */
	public String createUserAttention(){
		String attentionType=(String)httpServletRequest.getParameter("attentionType");
		Long userId;
		try{
			userId=Long.parseLong(httpServletRequest.getParameter("userId"));
		}catch(NullPointerException e){
			String warn="你所关注的资讯类型设置失败!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}
		String result=getUserAttention(userId);//根据用户ID获取用户资讯关注类型
		if(result!=null){//当result不为空时，表示该用户已经设置了资讯关注类型
			String warn="您的操作出错，请重新登录后再操作！";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}
		TUserAttention userAttention=new TUserAttention();
//		String[] attentionType = new String[3];
//		user=this.userService.getUser(TUser.class,userId);
		if(attentionType==null||attentionType==""){
			String warn="你所关注的资讯类型设置失败!";
			httpServletRequest.setAttribute("WARN", warn);
			return ERROR;
		}else{
			userAttention.setUserId(userId);
			userAttention.setAttentionArticleType(attentionType);
			this.userAttentionService.add(userAttention);
			return SUCCESS;
		}
	}
}
